import allFilds from "common/filds";
import btTable from "components/bt_table";
import {mockTableData, adapterCloudListData} from './data'
import { bootstrapTableColumns, getColumnsFromManager } from './columns'

function mkTable(config={}){
  let id = 'btTablex'
  let options = {}
  config.data = config.data || mockTableData

  Object.keys(config).forEach(ky=>{
    if (ky === 'id') id = config[ky]
    else {
      options[ky] = config[ky]
    }
  })

  // 生成表单实例
  const table = btTable({
    $$id: id,
    options
  })
  
  return table
}


// 生成aotoo表格组件实例
async function createTable(params) {
  const tableColumnsName = params.tableColumnsName
  const collectionName = params.collectionName
  const events = params.events


  let tableColumns = null
  if (collectionName === 'CLOUD-TABLE-MANAGER') {
    tableColumns = allFilds[collectionName]
  } else {
    tableColumns = await getColumnsFromManager({ collectionName: collectionName })
  }


  const bootstrapTable = mkTable({
    id: 'table-'+tableColumnsName,
    toolbar: '#toolbar-'+tableColumnsName,  //工具栏
    columns: bootstrapTableColumns({
      columns: tableColumns,
      columnsName: tableColumnsName,
      collectionName,
      events
    }, ()=>bootstrapTable),
    loadingTemplate: function() { return '<i class="icon-loading"></i>' },
    formatNoMatches:function(){  // 无数据返回
      return '<i class="icon-loading"></i>';
    }
  })
  bootstrapTable.__tableColumns = tableColumns
  return bootstrapTable
}

/**
 * 重新装载表格数据
 * @param {Object} table jquery表格对象
 * @param {*} init 是否对表格初始化
 */
export async function reloadTableData(table, init){
  const bootstrapTable = this.bt
  const TABLE_COLUMNS  = this.tableColumns
  const COLLECTIONS    = this.cloudCollection
  const cloudListData = await COLLECTIONS.doc.list()
  const res = adapterCloudListData(cloudListData.data, TABLE_COLUMNS)  // 云端数据适配
  if (init) {
    table = await bootstrapTable.getBootstrapTable('init')
  }
  table.bootstrapTable('load', res)   // 重新加载数据, 刷新表格
  table.bootstrapTable('hideLoading') // 关闭loading
}


export default createTable
